package com.afra.formutleview.sugar;

import android.content.Context;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.ViewGroup;

import com.afra.formutleview.R;
import com.afra.formutleview.base.BaseRecyclerAdapter;
import com.afra.formutleview.base.EventBusHelper;
import com.afra.formutleview.base.OnItemClickListener;
import com.afra.formutleview.base.ViewSugar;
import com.afra.formutleview.bean.BaseBean;
import com.afra.formutleview.bean.NeneGridBean;
import com.afra.formutleview.bean.NeneGridItemBean;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yangshuai on 2018/7/13.
 * {link http://afra55.github.io}
 */

public class NineGridSugar extends ViewSugar{

    public static ViewSugar getInstance(Context context, ViewGroup viewGroup) {
        return new NineGridSugar(context, viewGroup);
    }

    private RecyclerView recyclerView;

    public NineGridSugar(Context context, ViewGroup parent) {
        super(context, parent);
        recyclerView = findView(R.id.item_recycler_view_for_nine);
        GridLayoutManager layout = new GridLayoutManager(context, 3);
        recyclerView.setLayoutManager(layout);
    }

    @Override
    public int getLayoutId() {
        return R.layout.item_for_nine_grid;
    }

    @Override
    public <T extends BaseBean> void bind(T obj) {

        if (obj instanceof NeneGridBean) {
            NeneGridBean neneGridBean = (NeneGridBean) obj;
            List<NeneGridItemBean> list = neneGridBean.getList();
            if (list == null) {
                list = new ArrayList<>();
            }
            // 添加一个加号
            list.add(new NeneGridItemBean(""));
            BaseRecyclerAdapter<NeneGridItemBean> adapter = new BaseRecyclerAdapter<>(context);
            recyclerView.setAdapter(adapter);
            adapter.init(list);
            adapter.notifyDataSetChanged();
            adapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClicked(int position, Object obj) {
                    if (obj != null && obj instanceof NeneGridItemBean) {
                        NeneGridItemBean itemBean = (NeneGridItemBean) obj;
                        if (TextUtils.isEmpty(itemBean.getImagePath())) {
                            EventBusHelper.post("添加图片", getViewHolder().getAdapterPosition());
                        }
                    }
                }

                @Override
                public boolean onItemLongClicked(int position, Object obj) {
                    return false;
                }
            });
        }

    }
}
